<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();

// проверяем может ли данный пользователь просматривать заявки
if(!CModule::IncludeModule("iblock"))
{
    ShowError("Модуль Информационных блоков не установлен");
    return;
}

if (!$USER->IsAuthorized())
{
    ShowError("Вы должны авторизоваться, чтобы иметь возможность работать с заявками.");
    return;        
}

if (!(CSite::InGroup(array($arParams["GROUP_CLIENTS"])) || CSite::InGroup(array($arParams["GROUP_ADMINS"])) || CSite::InGroup(array($arParams["GROUP_PERFORMERS"]))))
{
    ShowError("У Вас нет доступа к заявкам. Обратитесь в отдел ИТО для предоставления Вам доступа.");
    return;        
}


if(!isset($arParams["CACHE_TIME"]))
	$arParams["CACHE_TIME"] = 60;

$arParams["IBLOCK_TYPE"] = trim($arParams["IBLOCK_TYPE"]);
if(strlen($arParams["IBLOCK_TYPE"])<=0)
	$arParams["IBLOCK_TYPE"] = "itrequests";

$arParams["ELEMENT_ID"] = intval($arParams["ELEMENT_ID"]);


if ($_SERVER["REQUEST_METHOD"]=="POST" && $_REQUEST["ID"]>0)
{  
    $uid = $USER->GetID();
    $uname = $USER->GetFullName();
    //$MESS["EMAIL_TO"] = $USER->GetEmail();
    
    if (CSite::InGroup(array($arParams["GROUP_ADMINS"])) || CSite::InGroup(array($arParams["GROUP_PERFORMERS"])))
        $isPerformer = true;
    else
        $isPerformer = false;

    if (strlen($_REQUEST["subscribe"]))
    {
        $request = GetIBlockElement($_REQUEST["ID"]);
        $subscribers = $request["PROPERTIES"]["SUBSCRIBERS"]["VALUE"];
        if (strlen($subscribers))
            $subscribers .= ";";
        $subscribers .= $uid;        
        CIBlockElement::SetPropertyValues($request["ID"], $request["IBLOCK_ID"], $subscribers, "SUBSCRIBERS");        
        
        $el = new CIBlockElement;
        $PROP = array();
        $PROP["REQUEST"] = $_REQUEST["ID"];
        $PROP["TYPE"] = $types["Системная"];
        $arLoadArray = Array(
            "MODIFIED_BY"       => $uid,
            "PROPERTY_VALUES"   => $PROP,
            "IBLOCK_ID"         => $arParams["IBLOCK_REQUESTS_LOGS_ID"],
            "NAME"              => "Системная запись к заявке #".$_REQUEST["ID"],
            "ACTIVE"            => "Y",
            "PREVIEW_TEXT"      => "Подписался на заявку",
            "PREVIEW_TEXT_TYPE" => "html"
        );
        if (!$el->Add($arLoadArray))
            echo "Error: ".$el->LAST_ERROR;
        
        LocalRedirect($_REQUEST["ID"].".php");
    }
    else
    if (strlen($_REQUEST["unsubscribe"]))
    {
        $request = GetIBlockElement($_REQUEST["ID"]);
        $subscribers = $request["PROPERTIES"]["SUBSCRIBERS"]["VALUE"];
        $subscribers = str_replace($uid, "", $subscribers);
        $subscribers = str_replace(";;", ";", $subscribers);
        CIBlockElement::SetPropertyValues($request["ID"], $request["IBLOCK_ID"], $subscribers, "SUBSCRIBERS");    
        
        $el = new CIBlockElement;
        $PROP = array();
        $PROP["REQUEST"] = $_REQUEST["ID"];
        $PROP["TYPE"] = $types["Системная"];
        $arLoadArray = Array(
            "MODIFIED_BY"       => $uid,
            "PROPERTY_VALUES"   => $PROP,
            "IBLOCK_ID"         => $arParams["IBLOCK_REQUESTS_LOGS_ID"],
            "NAME"              => "Системная запись к заявке #".$_REQUEST["ID"],
            "ACTIVE"            => "Y",
            "PREVIEW_TEXT"      => "Отписался от заявки",
            "PREVIEW_TEXT_TYPE" => "html"
        );
        if (!$el->Add($arLoadArray))
            echo "Error: ".$el->LAST_ERROR;        
        
        LocalRedirect($_REQUEST["ID"].".php");
    }
    
    $MESS = array(); // массив для отправки сообщений
    $MESS["WHAT_CHANGE"] = "";
    $MESS["MESSAGE_AUTHOR"] = $uname;
    $MESS["MESSAGE_AUTHOR_EMAIL"] = $USER->GetEmail();
    
    // выбираем свойства инфоблока для определения типа комментария
    $types = array();
    $prs = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$arParams["IBLOCK_REQUESTS_LOGS_ID"], "CODE"=>"TYPE"));
    while($field = $prs->GetNext())
    {
        $types[$field["VALUE"]] = $field["ID"];
    }
        
    // анализ состояний
    $PROP_R = array();
    $LOGTXT = "";
    $request = GetIBlockElement($_REQUEST["ID"]);
    $MESS["ID"] = $request["ID"];
    $MESS["TITLE"] = $request["NAME"];
    $MESS["DATE_CREATE"] = $request["DATE_CREATE"];
    $isCreator = ($request["CREATED_BY"]==$uid)?true:false;
    $rsUser = CUser::GetByID($request["CREATED_BY"]);    
    $pitem = $rsUser->Fetch();
    $MESS["OWNER_NAME"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
    $MESS["OWNER_EMAIL"] = $pitem["EMAIL"];
       
    if ($isPerformer && (IntVal($_REQUEST["CATEGORY_ID"])!=IntVal($request["PROPERTIES"]["CATEGORY"]["VALUE"])))
    {
        $PROP_R["CATEGORY"] = $_REQUEST["CATEGORY_ID"];
        $pitem = GetIBlockElement($PROP_R["CATEGORY"]);
        $LOGTXT .= "<li>категория: ".$pitem["NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "категория: ".$pitem["NAME"]."\r\n";
        $MESS["CATEGORY"] .= $pitem["NAME"];
    }
    else
    {
        $PROP_R["CATEGORY"] = $request["PROPERTIES"]["CATEGORY"]["VALUE"];
        $pitem = GetIBlockElement($PROP_R["CATEGORY"]);
        $MESS["CATEGORY"] .= $pitem["NAME"];
    }
    
    if ($isPerformer && (IntVal($_REQUEST["RESPONSIBLE_USER_ID"])!=IntVal($request["PROPERTIES"]["RESPONSIBLE_USER"]["VALUE"])))
    {
        $MESS["EMAIL_TO"] = "";
        // если сменился ответственный и ранее был другой, то письма обоим
        if (IntVal($request["PROPERTIES"]["RESPONSIBLE_USER"]["VALUE"]))
        {
            $rsUser = CUser::GetByID(IntVal($request["PROPERTIES"]["RESPONSIBLE_USER"]["VALUE"]));
            $pitem = $rsUser->Fetch();
            $MESS["EMAIL_TO"] .= $pitem["EMAIL"].",";
        }
        $PROP_R["RESPONSIBLE_USER"] = $_REQUEST["RESPONSIBLE_USER_ID"];
        $rsUser = CUser::GetByID($PROP_R["RESPONSIBLE_USER"]);
        $pitem = $rsUser->Fetch();
        $LOGTXT .= "<li>ответственный: ".$pitem["NAME"]." ".$pitem["LAST_NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "ответственный: ".$pitem["NAME"]." ".$pitem["LAST_NAME"]."\r\n";
        $MESS["RESPONSIBLE_USER"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
        $MESS["EMAIL_TO"] .= $pitem["EMAIL"];
    }
    else
    {
        $PROP_R["RESPONSIBLE_USER"] = $request["PROPERTIES"]["RESPONSIBLE_USER"]["VALUE"];
        $rsUser = CUser::GetByID($PROP_R["RESPONSIBLE_USER"]);
        $pitem = $rsUser->Fetch();
        $MESS["RESPONSIBLE_USER"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
        $MESS["EMAIL_TO"] = $pitem["EMAIL"];
    }
    
    if ($isPerformer && (IntVal($_REQUEST["STATUS_ID"])!=IntVal($request["PROPERTIES"]["STATUS"]["VALUE"])))
    {
        $PROP_R["STATUS"] = $_REQUEST["STATUS_ID"];
        $pitem = GetIBlockElement($PROP_R["STATUS"]);
        $LOGTXT .= "<li>статус: ".$pitem["NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "статус: ".$pitem["NAME"]."\r\n";
        $MESS["STATUS"] = $pitem["NAME"];
    }
    else
    {
        $PROP_R["STATUS"] = $request["PROPERTIES"]["STATUS"]["VALUE"];
        $pitem = GetIBlockElement($PROP_R["STATUS"]);
        $MESS["STATUS"] = $pitem["NAME"];
    }
    
    if ($isPerformer && (IntVal($_REQUEST["DIFFICULTY_ID"])!=IntVal($request["PROPERTIES"]["DIFFICULTY"]["VALUE"])))
    {
        $PROP_R["DIFFICULTY"] = $_REQUEST["DIFFICULTY_ID"];
        $pitem = GetIBlockElement($PROP_R["DIFFICULTY"]);
        $LOGTXT .= "<li>сложность: ".$pitem["NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "сложность: ".$pitem["NAME"]."\r\n";
        $MESS["DIFFICULTY"] = $pitem["NAME"];
    }
    else
    {
        $PROP_R["DIFFICULTY"] = $request["PROPERTIES"]["DIFFICULTY"]["VALUE"];
        $pitem = GetIBlockElement($PROP_R["DIFFICULTY"]);
        $MESS["DIFFICULTY"] = $pitem["NAME"];
    }
    
    if (($isPerformer||$isCreator) && (IntVal($_REQUEST["CRITICALITY_ID"])!=IntVal($request["PROPERTIES"]["CRITICALITY"]["VALUE"])))
    {
        $PROP_R["CRITICALITY"] = $_REQUEST["CRITICALITY_ID"];
        $pitem = GetIBlockElement($PROP_R["CRITICALITY"]);
        $LOGTXT .= "<li>критичность: ".$pitem["NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "критичность: ".$pitem["NAME"]."\r\n";
        $MESS["CRITICALITY"] = $pitem["NAME"];
    }
    else
    {
        $PROP_R["CRITICALITY"] = $request["PROPERTIES"]["CRITICALITY"]["VALUE"];
        $pitem = GetIBlockElement($PROP_R["CRITICALITY"]);
        $MESS["CRITICALITY"] = $pitem["NAME"];
    }

    if ($isCreator && (IntVal($_REQUEST["MARK_ID"])!=IntVal($request["PROPERTIES"]["MARK"]["VALUE"])))
    {
        $PROP_R["MARK"] = $_REQUEST["MARK_ID"];
        $pitem = GetIBlockElement($PROP_R["MARK"]);
        $LOGTXT .= "<li>оценка ответов: ".$pitem["NAME"]."</li>";
        $MESS["WHAT_CHANGE"] .= "оценка ответов: ".$pitem["NAME"]."\r\n";
        $MESS["RATE"] = $pitem["NAME"];
    }
    else
    {
        $PROP_R["MARK"] = $request["PROPERTIES"]["MARK"]["VALUE"];
        $pitem = GetIBlockElement($PROP_R["MARK"]);
        $MESS["RATE"] = $pitem["NAME"];
    }

    if ($isPerformer && (IntVal($_REQUEST["TO_WIKI_ID"])!=IntVal($request["PROPERTIES"]["TO_WIKI"]["VALUE"])))
    {
        $PROP_R["TO_WIKI"] = $_REQUEST["TO_WIKI_ID"];
        $pitem = CIBlockPropertyEnum::GetByID($PROP_R["TO_WIKI"]);
        $LOGTXT .= "<li>база знаний: ".$pitem["VALUE"]."</li>";
        $MESS["WHAT_CHANGE"] .= "база знаний: ".$pitem["VALUE"]."\r\n";
        $MESS["TO_WIKI"] = $pitem["VALUE"];
    }
    else
    {
        $PROP_R["TO_WIKI"] = $request["PROPERTIES"]["TO_WIKI"]["VALUE"];
        $pitem = CIBlockPropertyEnum::GetByID($PROP_R["TO_WIKI"]);
        $MESS["TO_WIKI"] = $pitem["VALUE"];
    }
    
    if (($arParams["USE_PROJECT"]=="Y") && ($isPerformer||$isCreator)) 
    {
        if (IntVal($_REQUEST["PROJECT_ID"])!=IntVal($request["PROPERTIES"]["PROJECT"]["VALUE"]))
        {
            $PROP_R["PROJECT"] = $_REQUEST["PROJECT_ID"];
            $pitem = GetIBlockElement($PROP_R["PROJECT"]);
            $LOGTXT .= "<li>проект: ".$pitem["NAME"]."</li>";
            $MESS["WHAT_CHANGE"] .= "проект: ".$pitem["NAME"]."\r\n";
            $MESS["PROJECT"] = $pitem["NAME"];
        }
        else
        {
            $PROP_R["PROJECT"] = $request["PROPERTIES"]["PROJECT"]["VALUE"];
            $pitem = GetIBlockElement($PROP_R["PROJECT"]);
            $MESS["PROJECT"] = $pitem["NAME"];
        }
    }
    else
        $MESS["PROJECT"] = "";
    
    if ($_REQUEST["CLOSE"]=="Y")
    {
        $PROP_R["USER_CLOSE"] = $uid;
        $PROP_R["DATE_CLOSE"] = date("d.m.Y h:i:s");
        $LOGTXT .= "<li>обращение закрыто</li>";
        $MESS["WHAT_CHANGE"] .= "обращение закрыто\r\n";
    }
    elseif ($_REQUEST["OPEN"]=="Y")
    {
        $PROP_R["USER_CLOSE"] = "";
        $PROP_R["DATE_CLOSE"] = "";
        $LOGTXT .= "<li>обращение открыто</li>";
        $MESS["WHAT_CHANGE"] .= "обращение открыто\r\n";
    }
    else
    {
        $PROP_R["USER_CLOSE"] = $request["PROPERTIES"]["USER_CLOSE"]["VALUE"];
        $PROP_R["DATE_CLOSE"] = $request["PROPERTIES"]["DATE_CLOSE"]["VALUE"];
    }

    // выбираем админов техподдержки для отправки копий сообщений
    $filter = Array("GROUPS_ID" => Array($arParams["GROUP_ADMINS"]));
    $rsUsers = CUser::GetList(($by="last_name"), ($order="asc"), $filter);         
    $MESS["EMAIL_ADMIN_TO"] = "";
    while ($res = $rsUsers->GetNext())
    {
        $MESS["EMAIL_ADMIN_TO"] .= $res["EMAIL"].",";
    }
    
    // если есть подписчики, то добавляем и их в рассылку
    $MESS["SUBSCRIBE_EMAIL"] = "";
    $subscribers = explode(";", $request["PROPERTIES"]["SUBSCRIBERS"]["VALUE"]);
    foreach($subscribers as $user)
    {
        if ($user>0)
        {
            $rsUser = CUser::GetByID($user);
            $arUser = $rsUser->Fetch();
            $MESS["SUBSCRIBE_EMAIL"] .= ",".$arUser["EMAIL"];
        }
    }    
    
    // создание элемента сообщения с файлами в ходе исполнения
    $el = new CIBlockElement;
    
    $PROP = array();
    $PROP["REQUEST"] = $_REQUEST["ID"];
    
    if ($_REQUEST["HIDDEN"]=="Y")
        $PROP["TYPE"] = $types["Комментарий скрытый"];
    else
        $PROP["TYPE"] = $types["Комментарий"];

    foreach($_FILES as $file)
    {
        if ($file["error"]==0)
            $PROP["FILE"][] = $file;
    }

    $txt = str_replace("\n", "<br />", $_REQUEST["MESSAGE"]);
    $txt = str_replace("<QUOTE>", "<table class='quotetable' width='95%' border='0' cellpadding='3' cellspacing='1'><tr><td class='tdquotehead'>Цитата</td></tr><tr><td class='tdquote'>", str_replace("</QUOTE>", "</td></tr></table>", $txt));
    
    $adderror = false;
    if (strlen($txt) || count($PROP["FILE"]))
    {

        $arLoadArray = Array(
            "MODIFIED_BY"       => $uid,
            "PROPERTY_VALUES"   => $PROP,
            "IBLOCK_ID"         => $arParams["IBLOCK_REQUESTS_LOGS_ID"],
            "NAME"              => "Комментарий к заявке #".$_REQUEST["ID"]." пользователя ".$uname,
            "ACTIVE"            => "Y",
            "PREVIEW_TEXT"      => $txt,
            "PREVIEW_TEXT_TYPE" => "html"
        );
        if (!$s_id = $el->Add($arLoadArray))
        {
            echo "Ошибка: ".$el->LAST_ERROR;
            $adderror = true;
        }
    }
    
    if (!$adderror)
    {
        // создание системной записи и изменение параметров запроса
        if (strlen($LOGTXT))
        {
            $el = new CIBlockElement;
            $PROP = array();
            $PROP["REQUEST"] = $_REQUEST["ID"];
            $PROP["TYPE"] = $types["Системная"];

            $arLoadArray = Array(
                "MODIFIED_BY"       => $uid,
                "PROPERTY_VALUES"   => $PROP,
                "IBLOCK_ID"         => $arParams["IBLOCK_REQUESTS_LOGS_ID"],
                "NAME"              => "Системная запись к заявке #".$_REQUEST["ID"],
                "ACTIVE"            => "Y",
                "PREVIEW_TEXT"      => "<ul>".$LOGTXT."</ul>",
                "PREVIEW_TEXT_TYPE" => "html"
            );
            if ($s_id=$el->Add($arLoadArray))
            {
                $new_el = GetIBlockElement($s_id);
                $MESS["TIMESTAMP"] = $new_el["DATE_CREATE"];
            }
            else
                echo "Error: ".$el->LAST_ERROR;


            $el = new CIBlockElement;

            $arLoadArray = Array(
                "MODIFIED_BY"    => $uid,
                "PROPERTY_VALUES"=> $PROP_R,
            );
            if (!$el->Update($_REQUEST["ID"], $arLoadArray))
                echo "Error: ".$el->LAST_ERROR;
        }

        // отправка уведомлений всем участникам
        if (strlen($txt) || count($PROP["FILE"]))
        {
            $MESS["MESSAGE_HEADER"] = ">======================= СООБЩЕНИЕ ===================================\r\n";
            $MESS["MESSAGE_BODY"] = str_replace("<br />", "\r\n", $txt);
            $MESS["MESSAGE_FOOTER"] = "\r\n>=====================================================================\r\n";
        }
        else
            $MESS["MESSAGE_HEADER"] = $MESS["MESSAGE_BODY"] = $MESS["MESSAGE_FOOTER"] = "";

        if (strlen($MESS["WHAT_CHANGE"]))
        {
            $MESS["WHAT_CHANGE"] = ">======================= ИЗМЕНЕНИЯ ===================================\r\n".$MESS["WHAT_CHANGE"].">=====================================================================\r\n\r\n";
        }

        $arEventFields = array(
            "ID"                  => $MESS["ID"],
            "EMAIL_TO"            => $MESS["EMAIL_TO"],
            "EMAIL_ADMIN_TO"      => $MESS["EMAIL_ADMIN_TO"],
            "TIMESTAMP"           => $MESS["TIMESTAMP"],
            "TITLE"               => $MESS["TITLE"],
            "MESSAGE_AUTHOR"      => $MESS["MESSAGE_AUTHOR"],
            "OWNER_NAME"          => $MESS["OWNER_NAME"],
            "CATEGORY"            => $MESS["CATEGORY"],
            "STATUS"              => $MESS["STATUS"],
            "CRITICALITY"         => $MESS["CRITICALITY"],
            "DIFFICULTY"          => $MESS["DIFFICULTY"],
            "DATE_CREATE"         => $MESS["DATE_CREATE"],
            "RESPONSIBLE_NAME"    => $MESS["RESPONSIBLE_USER"],
            "RATE"                => $MESS["RATE"],
            "PROJECT"             => $MESS["PROJECT"],
            "WHAT_CHANGE"         => $MESS["WHAT_CHANGE"],
            "MESSAGE_HEADER"      => $MESS["MESSAGE_HEADER"],        
            "FILES_LINKS"         => "",
            "MESSAGE_BODY"        => $MESS["MESSAGE_BODY"],
            "MESSAGE_FOOTER"      => $MESS["MESSAGE_FOOTER"],
        );
        CEvent::Send($arParams["MAIL_TEMPL_PREFIX"]."_CHANGE_FOR_TP", "s1", $arEventFields, "N");  // сотруднику техподдержки              

        if ($isPerformer)
        {
            $arEventFields["EMAIL_TO"] = $MESS["OWNER_EMAIL"].$MESS["SUBSCRIBE_EMAIL"];
            CEvent::Send($arParams["MAIL_TEMPL_PREFIX"]."_CHANGE_BY_TP_FOR_AUTHOR", "s1", $arEventFields, "N");        
        }
        else
        if (($arParams["SHARE_LIST"]=="Y")&&!$isCreator)
        {
            $arEventFields["EMAIL_TO"] = $MESS["MESSAGE_AUTHOR_EMAIL"].",".$MESS["OWNER_EMAIL"].$MESS["SUBSCRIBE_EMAIL"];
            CEvent::Send($arParams["MAIL_TEMPL_PREFIX"]."_CHANGE_BY_AUTHOR_FOR_AUTHOR", "s1", $arEventFields, "N");                    
        }
        else
        {
            $arEventFields["EMAIL_TO"] = $MESS["OWNER_EMAIL"].$MESS["SUBSCRIBE_EMAIL"];
            CEvent::Send($arParams["MAIL_TEMPL_PREFIX"]."_CHANGE_BY_AUTHOR_FOR_AUTHOR", "s1", $arEventFields, "N");        
        }
    }
    
//echo "<pre>";
//print_r($MESS);
//print_r($arEventFields);
//print_r($PROP_R);
//echo "</pre>";
    
    if (strlen($_REQUEST["save"]))
        LocalRedirect("index.php");
    else
        LocalRedirect($_REQUEST["ID"].".php");
}

//if($this->StartResultCache(false, array($USER->GetGroups())))
{
       
    $userid = $USER->GetID();
    
    $arSelect = Array(
        "ID",
        "NAME",
        "DATE_CREATE",
        "CREATED_BY",
        "PROPERTY_CATEGORY",
        "PROPERTY_STATUS",
        "PROPERTY_RESPONSIBLE_USER",
        "PROPERTY_DIFFICULTY",
        "PROPERTY_CRITICALITY",
        "PROPERTY_MARK",
        "PROPERTY_PROJECT",
        "PROPERTY_USER_CLOSE",
        "PROPERTY_DATE_CLOSE",
        "PROPERTY_TO_WIKI",
        "PROPERTY_SUBSCRIBERS"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_ID"],
        "ACTIVE" => "Y",
        "ID" => $arParams["ELEMENT_ID"],
    );

    $rsElement = CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect);
    
    if($arResult = $rsElement->GetNext())
    {        
        $arResult["ISADMIN"] = CSite::InGroup(array($arParams["GROUP_ADMINS"]));
        $arResult["ISPERFORMER"] = CSite::InGroup(array($arParams["GROUP_PERFORMERS"]));   
        $arResult["ISCREATOR"] = ($arResult["CREATED_BY"]==$userid) ? true : false;
               
        if (!$arResult["ISADMIN"] && !$arResult["ISPERFORMER"] && (($arResult["CREATED_BY"]!=$userid)&&($arParams["SHARE_LIST"]!="Y")))
        {
        //    $this->AbortResultCache();
            ShowError("У Вас нет доступа к данной заявке.");
            return;        
        }
        
        // выбираем подписчиков
        $subscribers = explode(";", $arResult["PROPERTY_SUBSCRIBERS_VALUE"]);
        
        if (($arParams["SHARE_LIST"]=="Y") && !$arResult["ISADMIN"] && !$arResult["ISPERFORMER"] && !$arResult["ISCREATOR"])
            if (in_array($userid, $subscribers))
                $arResult["SHOW_SUBSCRIBE"] = "2";
            else
                $arResult["SHOW_SUBSCRIBE"] = "1";
        else 
            $arResult["SHOW_SUBSCRIBE"] = "0";

        foreach($subscribers as $user)
        {
            if ($user>0)
            {
                $rsUser = CUser::GetByID($user);
                $arResult["SUBSCRIBERS"][] = $rsUser->Fetch();
            }
        }
        
        // *************************************************************************
        // выбираем все справочники
        // *************************************************************************
        
        // категории
        $arSelect = Array(
            "ID",
            "NAME",
            "PROPERTY_DEFAULT_RESPONSIBLE"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CATEGORY"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            if ($arItem["ID"]==$arResult["PROPERTY_CATEGORY_VALUE"])
                $arResult["CATEGORY_NAME"] = $arItem["NAME"];
            
            $arResult["HANDBOOKS"]["CATEGORY"][] = $arItem;            
        }        
        
        // статусы
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_STATUSES"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            if ($arItem["ID"]==$arResult["PROPERTY_STATUS_VALUE"])
                $arResult["STATUS_NAME"] = $arItem["NAME"];
            
            $arResult["HANDBOOKS"]["STATUSES"][] = $arItem;            
        }        
        
        // критичность
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CRITICALITY"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            if ($arItem["ID"]==$arResult["PROPERTY_CRITICALITY_VALUE"])
                $arResult["CRITICALITY_NAME"] = $arItem["NAME"];
            
            $arResult["HANDBOOKS"]["CRITICALITY"][] = $arItem;            
        }        

        // сложность
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_DIFFICULTY"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            $arResult["HANDBOOKS"]["DIFFICULTY"][] = $arItem;            
        }   

        // оценки ответов
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_MARK"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            $arResult["HANDBOOKS"]["MARK"][] = $arItem;            
        }   
        
        if ($arParams["USE_PROJECT"]=="Y")
        {
            // проекты
            $arSelect = Array(
                "ID",
                "NAME"
            );

            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_PROJECT"],
                "ACTIVE" => "Y",
            );
            $arSort = array("SORT"=>"ASC");

            $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
            while($arItem = $rsElement->GetNext())
            {
                if ($arItem["ID"]==$arResult["PROPERTY_PROJECT_VALUE"])
                    $arResult["PROJECT_NAME"] = $arItem["NAME"];
                
                $arResult["HANDBOOKS"]["PROJECT"][] = $arItem;            
            }   
        }
        
        // варианты добавления в базу знаний
        $property_enums = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$arParams["IBLOCK_REQUESTS_ID"], "CODE"=>"TO_WIKI"));
        while($enum_fields = $property_enums->GetNext())
        {
            $arResult["HANDBOOKS"]["TO_WIKI"][] = $enum_fields;
        }
        
        // *************************************************************************
        // выбираем пользователей техподдержки + админы
        // *************************************************************************
        $performers = array();
        $filter = Array("GROUPS_ID" => Array($arParams["GROUP_ADMINS"], $arParams["GROUP_PERFORMERS"]));
        $rsUsers = CUser::GetList(($by="last_name"), ($order="asc"), $filter);         
        while ($user = $rsUsers->GetNext())
        {
            $arResult["PERFORMERS"][] = $user;
            $performers[] = $user["ID"];
        }
                       
        // дата создания
        list($arResult["DATE"], $arResult["TIME"]) = explode(" ", $arResult["DATE_CREATE"]);
        
        // дата закрытия
        if (strlen($arResult["PROPERTY_DATE_CLOSE_VALUE"]))
        {
            $arResult["CLOSED"] = true;
            // кто закрыл
            if ($arResult["PROPERTY_NAME_CLOSE_VALUE"])
            {
                $rsUser = CUser::GetByID($arResult["PROPERTY_NAME_CLOSE_VALUE"]);
                $arResult["NAME_CLOSE"] = $rsUser->Fetch();
            }
            // дата закрытия
            $arResult["DATE_CLOSE"] = $arResult["PROPERTY_DATE_CLOSE_VALUE"];
        }
        
        // создатель обращения
        $rsUser = CUser::GetByID($arResult["CREATED_BY"]);
        $arResult["CREATOR"] = $rsUser->Fetch();
                
        $res = CIBlockSection::GetByID($arResult["CREATOR"]["UF_DEPARTMENT"][0]);
        $department = $res->GetNext();
        $arResult["CREATOR"]["DEPARTMENT"] = $department["NAME"];
        
        // ответственный исполнитель
        if ($arResult["PROPERTY_RESPONSIBLE_USER_VALUE"]>0)
        {
            $rsUser = CUser::GetByID($arResult["PROPERTY_RESPONSIBLE_USER_VALUE"]);
            $arResult["RESPONSINLE_USER"] = $rsUser->Fetch();
        }
        
/*        
        if (in_array($arResult["PROPERTY_STATUS_ENUM_ID"], array("50", "51", "52")))
            $arResult["CAN_COMMENT"] = false;
        else
            $arResult["CAN_COMMENT"] = true;              
        
        $rsUser = CUser::GetByID($arResult["PROPERTY_PERFORMER_VALUE"]);
        if ($arUser = $rsUser->Fetch())
            $arResult["PERFORMER"] = $arUser["NAME"]." ".$arUser["LAST_NAME"];             
  */      
        
        
        
        // выбор информации из хода исполнения
        $arSelect = Array(
            "ID",
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_LOGS_ID"],
            "ACTIVE" => "Y",
            "PROPERTY_REQUEST" => $arResult["ID"],
        );

        $arSort = array("DATE_CREATE"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);        
        
        while($arItem = $rsElement->GetNext())
        {
            $item = GetIBlockElement($arItem["ID"]);

            // создатель сообщения
            $rsUser = CUser::GetByID($item["CREATED_BY"]);
            if ($arUser = $rsUser->Fetch())
            {
                $item["CREATOR"] = $arUser["NAME"]." ".$arUser["LAST_NAME"];
                $item["IS_SUPPORT"] = in_array($arUser["ID"], $performers);
            }
            
            // записываем дату последнего сообщения и автора для шапки детального просмотра
            $arResult["LAST_DATE"] = $item["DATE_CREATE"];
            $arResult["LAST_USER"] = $item["CREATOR"];
                    
            // по типу сообщения определяем цвета и как выводить в списке сообщений
            $add_to_result = true;
            
            if ($item["PROPERTIES"]["TYPE"]["VALUE"] == "Комментарий")
            {
                if ($item["IS_SUPPORT"])
                {
                    $item["BGCOLOR"] = "#FDF9E1";
                }
                else
                {
                    $item["BGCOLOR"] = "#FFF";
                }                    
            }
            elseif ($item["PROPERTIES"]["TYPE"]["VALUE"] == "Комментарий скрытый")
            {
                $item["BGCOLOR"] = "#F1F8F5";
                $item["HIDDEN"] = true;
                if (!($arResult["ISADMIN"] || $arResult["ISPERFORMER"]))
                    $add_to_result = false;
            }
            elseif ($item["PROPERTIES"]["TYPE"]["VALUE"] == "Системная")                
            {                
                $item["BGCOLOR"] = "#F8F9FC";
                $item["SYSTEM"] = true;                
            }
            
            // определяем есть ли вложенные файлы в сообщении
            
            if (is_array($item["PROPERTIES"]["FILE"]["VALUE"]))
            {
                $a = array("б", "кб", "Мб", "Гб");
                foreach ($item["PROPERTIES"]["FILE"]["VALUE"] as $key => $value) 
                {
                    $item["PROPERTIES"]["FILE"]["VALUE"][$key] = CFile::GetFileArray($value);
                    $pos = 0;
                    $size = $item["PROPERTIES"]["FILE"]["VALUE"][$key]["FILE_SIZE"];
                    while($size >= 1024)
                    {
                        $size /= 1024;
                        $pos++;
                    }
                    $item["PROPERTIES"]["FILE"]["VALUE"][$key]["FILE_SIZE_TEXT"] = round($size,2)." ".$a[$pos];
                }
            }
                       
            if ($add_to_result)
                $arResult["LOGS"][] = $item;
        }
            
        $this->IncludeComponentTemplate();
    }
    else
    {
        $this->AbortResultCache();
        ShowError("Заявка не найдена!");
        @define("ERROR_404", "Y");
    }
}

if ($arResult)
    $APPLICATION->SetTitle("Заявка №".$arResult["ID"]." от ".$arResult["DATE"]);

//if ($USER->IsAdmin())
//{
//echo "<pre>";
//print_r($arResult);
//print_r($_REQUEST);
//echo "</pre>";
//}
?>
